//index.js
//获取应用实例

import ArticleAC from '../../js/article_access'

//公共定义
const app = getApp()

var util = require('../../utils/util.js');

Page({
  data: {
    motto: 'OoMabc 界面',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    background: ['/image/swiper-1.png', '/image/swiper-2.png', '/image/swiper-3.png'],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 3000,
    duration: 500,
    pageNo : 1,
    currentPageDataList : []
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  loadHomeList: function (p, cb) {
    var thisObj = p.thisObj;
    var pageNo = p.pageNo || this.data.pageNo || 1;
    this.setData({
      pageNo : pageNo
    });

    if(p.initList) {
      //清空列表存储变量
      this.setData({
        currentPageDataList: []
      });
    }

    wx.showLoading();

    ArticleAC.getArticles({
      maxLen : 340,
      albums : 1,
      pageSize : 15,
      pageNo : pageNo,
      hilightTag : 'HHtextHH',
      keyword : (this.data.queryWord || '')
    }, function(res) {
      console.log('getArticles', res);
        if (res && res.list) {
          var list = res.list;

          var currentList = thisObj.data.currentPageDataList;

          console.log('currentList', currentList);
          for (var i in list) {
            var obj = list[i];
            var content = obj.content || '';

            currentList.push({
              id: obj.id,
              splitTitleList: thisObj.splitTitle(obj.title),
              title: obj.title,
              dtime:
                //obj.updateTimeString
                '',
              info: content,
              splitInfo: thisObj.splitTitle(content),
              viewCount: obj.viewCount,
              tags: obj.tags,
              articleImg: (obj.thumbnailImgUrl && obj.thumbnailImgUrl + '_200X120' || app.globalData.defaultLogoImg)
            });
          }

          var albums = res.albums || [];
          if (albums) {
            for (var i in albums) {
              var album = albums[i];
              album.logo = album.logo + '_140X200';
            }
          }
          thisObj.setData({
            homeList: currentList,
            albumList: albums
          });
        } else {
          if (p.initList) {
            thisObj.setData({
              homeList: []
            });
          }
          thisObj.setData({
            pageNo: thisObj.data.pageNo - 1 || 1
          });
        }

        wx.hideLoading();

        if (cb) {
          cb();
        }
    });

  },
  onLoad: function (options) {
    this.loadData();
  },
  onShow : function() {

    this.loadData();

    this.loadHomeList({
      thisObj: this,
      initList: true,
      pageNo: 1 //下拉刷新第一页
    }, function () {
      
    });
  },
  loadData : function() {

    var word = app.globalData.queryWord || '';
    console.log('word', word);

    // 参数复制
    var temp = app.globalData.statusBar;

    if (word && word.length > 0) {
      temp.queryWord = word;
    } else {
      temp.queryWord = app.globalData.searchDefaultPlacehoder;
    }
    this.setData({
      queryWord: word
    });

    this.setData(
      {
        barStatus: temp
      }
    );

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }


  },
  get2UserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  clickAndShow: function (e) {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths);

        wx.previewImage({
          current: res.tempFilePaths[0], // 当前显示图片的http链接
          urls: res.tempFilePaths // 需要预览的图片http链接列表
        });

        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success: function (res) {
            console.log(res.width)
            console.log(res.height)
          }
        });
      }
    })
  },
  onPullDownRefresh: function () {

    this.loadHomeList({
      thisObj : this,
      initList : true,
      pageNo : 1 //下拉刷新第一页
    }, function() {
      console.log('stopPullDownRefresh');
      wx.stopPullDownRefresh();
    });
  },

  /*** 详情跳转 */
  clickListItem: function (event) {
    util.clickListItemAndJump(event);
  },

  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },

  clickSearchInput : function(e) {
    app.clickSearchInput(e);
  }

  ,splitTitle : function(s) {
    var rslist = [];

    var arr1 = s.split('HHtextHHS');

    for (var i in arr1) {
      var word1 = arr1[i];
      if (word1 && word1.length > 0) {
        var indexEnd = word1.indexOf('HHtextHHE');
        if (indexEnd >= 0) {
          rslist.push({
            content: word1.substring(0, indexEnd),
            type: 1
          });

          var wordEnd = word1.substring(indexEnd + 9);
          if (wordEnd && wordEnd.length > 0) {
            rslist.push({
              content: wordEnd,
              type: 0
            });
          }
        } else {
          rslist.push({
            content: word1,
            type: 0
          });
        }
      }
    }

    return rslist;
  }

  , onReachBottom : function () {
    console.log('next page on bottom');

    this.loadHomeList({
      thisObj: this,
      pageNo : this.data.pageNo + 1
    });
  },
  /*** 专辑详情跳转 */
  clickAlbumItem: function (event) {
    util.clickAlbumItemAndJump(event);
  }
})
